package com.zhq.security.auth.config;


import com.zhq.security.auth.handler.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Bean
    PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .formLogin().loginProcessingUrl("/login")
                .successHandler(new SuccessHandler())
                .and()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/defaultImg").permitAll()  //放行验证码
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new JWTAuthenticationHandler(), UsernamePasswordAuthenticationFilter.class)
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .logout().addLogoutHandler(new LogOutHandler())
                .logoutUrl("/singLogout")   //登出地址
                .logoutSuccessHandler(new MyLogoutSuccessHandler())   //登出成功处理
                ;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //放行swaggger
        web.ignoring().antMatchers("/assets/**", "/css/**",
                "/swagger-ui.html",
                "/webjars/**",
                "/v2/**",
                "/swagger-resources/**",
                "/images/**",
                "/doc.html");
    }
}
